<template>
  <div class="aside-menu">
    <div class="home-wrap">
      <menu-item :menu="home">
        <template #icon>
          <iconfont :size="28" :icon="home.icon"></iconfont>
        </template>
      </menu-item>
    </div>
    <div class="catalog">
      <div flex="cross:center">
        <iconfont icon="unorderedlist" :size="28" />
        <span class="ml-5">目录</span>
      </div>
      <div class="collapse">
        <b-tooltip :content="collapse ? '全部展开' : '全部折叠'">
          <iconfont
            :icon="collapse ? 'expand' : 'collapse'"
            :size="28"
            type="btn"
            @click="toggleCollapse"
          />
        </b-tooltip>
      </div>
    </div>
    <div class="menu-list">
      <b-scrollbar>
        <div class="menu-group" v-for="(menu, menuIndex) in menuList" :key="menuIndex">
          <menu-item v-if="!menu.children" :menu="menu" />
          <submenu :opens="opens" v-else :menu="menu" />
        </div>
      </b-scrollbar>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Menus',
}
</script>

<script setup>
import MenuItem from './menu-item.vue'
import Submenu from './sub-menu.vue'
import { useRoute } from 'vue-router'
import { ref, provide } from 'vue'
import { menuList, flatMenus } from '@/router/menus'

import mitt from 'mitt'
const emitter = mitt()

const home = { name: 'home', title: '首页', icon: 'home' }
const collapse = ref(true) // 全部收起

function toggleCollapse() {
  collapse.value = !collapse.value
  emitter.emit('collapseAll', collapse.value)
}

const route = useRoute()
const opens = ref([])

// 根据当前的路由，设置当前展开的层级索引
function calcOpens() {
  if (route.name === 'home') return
  const currentMenu = flatMenus.find(i => i.node.name === route.name)
  if (currentMenu) {
    opens.value = currentMenu.parents
  }
}
calcOpens()

provide('MenuEmitter', {
  emitter,
})
</script>

<style lang="stylus" scoped>
.catalog {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 8px;
  border-radius: 6px;
  position: relative;
  color: #262626;
  .collapse {
    > .icon-wrapper {
      &:hover {
        background: #f4f5f5;
      }
    }
  }
}
.menu-list {
  height: calc(100% - 82px);
}
.menu-group {
  padding: 0 8px;
  color: #262626;
}
.home-wrap {
  padding: 0 8px;
  margin-top: 8px;
}
</style>
